/* 
 * File:   main.cpp
 * Author: adrian
 *
 * Created on April 9, 2011, 4:36 PM
 */

#include <cstdlib>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
using namespace std;

int fd;//file descriptor for port

//function prototypes
int openPort();
int configPort();

int main()
{
	int port, wr, rd, cfg;
	char data[4];
	int reply;

	port = openPort();
	cfg = configPort();

	if (port < 0)
	{
            close(fd);
	}
        else if (cfg < 0)
        {
            close(fd);
        }
	else
	{
            while(data[0] != 'q')
            {
                cout << "Type data, or q to quit\n";
                cin >> data;
                cout << "Data: " << data << "\n";

                wr = write(fd, &data, 4);

                if (wr < 0)
                {
                    cerr << "Write failed\n";
                    return -1;
                }
                rd = read(fd, &reply, 1);
                while (rd == 0)
                {
                    //cerr << "Read failed\n";
                    rd = read(fd, &reply, 1);
                }
                cout << "Read: " << reply << "\n";
            }
	}

	close(fd);
        cout << "Program ended, device closed\n";
	return 0;
}

int openPort()
{
    fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY | O_NDELAY);
    if (fd == -1)
    {
        cerr << "Unable to open port\n";
        return -1;
    }
    else
    {
        fcntl(fd, F_SETFL, 0);
        //fcntl(fd, F_SETFL, FNDELAY);
        cout << "Port opened succesfully\n";
    }
    return 0;
}

int configPort()
{
    struct termios options;
    //Get the current options for the port...
    tcgetattr(fd, &options);
    //set baudrate
    cfsetispeed(&options, 9600);
    cfsetospeed(&options, 9600);
    //set parity checking
    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;

    //options.c_cc[VTIME]    = 0;   /* inter-character timer unused */
    //options.c_cc[VMIN]     = 4;   /* blocking read until 4 chars received */

    int n = tcsetattr(fd, TCSANOW, &options);
    if (n<0)
    {
        cerr << "Port configuration fail\n";
        return n;
    }
    else
        return 0;
}

